<template>
  <div id="questionnaire">
    <div v-if="subSuccess" style="text-align: center; padding-top: 200px;" :style="{minHeight: minheight}">
      <van-icon name="checked" class="success" />
      <p style="line-height: 40px; font-size: 14px;">感谢您的反馈</p>
      <p style="line-height: 60px; font-size: 18px;">提交成功</p>
    </div>
    <div v-if="!subSuccess">
      <p class="title">疫苗知多少问卷调查</p>
      <!--<p class="des">艾美汉信疫苗（大连）有限公司，始建于1993年9月，是国内起步较早的一家专业从事疫苗生产</p>-->

      <div>
        <van-cell-group>
          <van-cell title="学校所在地区" isLink :value="area || '请选择'" @click="showAddress = true" />
          <van-cell title="学校类型" isLink :value="schoolsType.text || '请选择'" @click="handleShowSchoolsType" />
          <van-cell title="学校名称" isLink :value="schools.text || '请选择'" @click="handleShowSchools" />
          <van-cell title="所在年级" isLink :value="grade.text || '请选择'" @click="handleShowGrade" />
          <van-cell title="所在班级" isLink :value="classes.text || '请选择'" @click="handleShowClasses" />
          <van-field
            v-model="realName"
            label="学生姓名"
            icon="clear"
            placeholder="请输入您的姓名"
            @click-icon="realName = ''"
          />
          <van-field
            v-model="tel"
            label="联系电话"
            icon="clear"
            type="tel"
            :maxLength="11"
            placeholder="请输入手机号"
            @click-icon="tel = ''"
          />
        </van-cell-group>

        <div class="question" v-for="(item, index) in question" :key="index">
          <div class="item">
            <p class="wen">问</p>
            <div class="title">{{item.question}}</div>
            <div class="daan">
              <van-radio-group :value="answer[index].a[0]" v-if="item.type == 1">
                <van-radio @click="radioClick(index, idx)" :name="idx" :key="idx" class="radio" v-for="(ans, idx) in item.answer">{{ans}}</van-radio>
              </van-radio-group>

              <van-checkbox-group :value="answer[index].a" v-if="item.type == 2">
                <van-checkbox
                  class="radio"
                  v-for="(ans, idx) in item.answer"
                  :key="idx"
                  @click.native="checkedClick(index, idx)"
                  :name="idx"
                >
                  {{ ans }}
                </van-checkbox>
              </van-checkbox-group>
            </div>
          </div>

        </div>


        <div style="padding: 10px 0px;">
          <van-button class="border-radius" style="border: 0.5px solid #fff;" size="normal" type="primary" block :loading="subLoading" @click.native="submit">提交问卷</van-button>
        </div>


        <AreaPicker
          v-model="showAddress"
          @onConfirm="handleAreaCofirm"
        ></AreaPicker>

        <van-popup v-model="showSchoolsType" position="bottom" :close-on-click-overlay="false">
          <van-picker show-toolbar title="选择学校类型" @confirm="onSchoolsTypeConfirm" @cancel="showSchoolsType = false" :columns="schoolsTypeData" />
        </van-popup>

        <van-popup v-model="showSchools" position="bottom" :close-on-click-overlay="false">
          <van-picker show-toolbar title="选择学校" @confirm="onSchoolsConfirm" @cancel="showSchools = false" :columns="schoolsData" />
        </van-popup>
        <van-popup v-model="showGrade" position="bottom" :close-on-click-overlay="false">
          <van-picker show-toolbar title="选择年级" @confirm="onGradeConfirm" @cancel="showGrade = false" :columns="gradeData" />
        </van-popup>

        <van-popup v-model="showClasses" position="bottom" :close-on-click-overlay="false">
          <van-picker show-toolbar title="选择班级" @confirm="onClassesConfirm" @cancel="showClasses = false" :columns="classesData" />
        </van-popup>

      </div>

    </div>
  </div>
</template>
<script>
  import schema from 'async-validator'
  import AreaPicker from "@/components/AreaPicker.vue"
  import { RadioGroup, Radio,  Checkbox, CheckboxGroup, Icon  } from 'vant'

  const descriptor = {
    provinceId: {required: true, message: '请选择所在地区'},
    cityId: {required: true, message: '请选择所在地区'},
    districtId: {required: true, message: '请选择所在地区'},
    schoolTypeId: {required: true, message: '请选择学校类型', min: 1},
    schoolId: {required: true, message: '请选择学校', min: 1},
    gradeId: {required: true, message: '请选择年级', min: 1},
    classId: {required: true, message: '请选择班级', min: 1},
    realName: {required: true, message: '请填写姓名'},
    mobile: [
      {required: true, message: '请填写手机号码'},
      {validator: function (rule, value, callback, source, options) {
          var reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
          var errors = [];
          if(!reg.test(value)) {
            errors.push('请填写正确的手机号码')
          }
          callback(errors);
        }}
    ],
    answers: [
      {required: true, message: '请完成问卷后提交'},
      {validator: function (rule, value, callback, source, options) {
          let isNull = false
          for (let i = 0, len = value.length; i < len; i++) {
            if (!value[i].a.length) {
              isNull = true
              break
            }
          }
          let errors = []
          if(isNull) {
            errors.push('请完成问卷后提交')
          }
          callback(errors)
        }}
    ],
  }
  const validator = new schema(descriptor)

  export default {
    components: {
      AreaPicker,
      [RadioGroup.name]: RadioGroup,
      [Radio.name]: Radio,
      [Checkbox.name]: Checkbox,
      [CheckboxGroup.name]: CheckboxGroup,
      [Icon.name]: Icon
    },
    computed: {
      schoolsTypeId() {
        return this.schoolsType.id
      },
      schoolsId() {
        return this.schools.id
      },
      classesId() {
        return this.classes.id
      },
      gradeId() {
        return this.grade.id
      },
    },
    created() {
      this.$http('/api/question/content').then(data => {
        this.question = data
        let answer = Array.from(data, x => ({
          q: x.id,
          a: []
        }))
        this.answer = answer
      }).catch(err => {

      })
    },
    data() {
      return {
        subSuccess: false,
        minheight: document.documentElement.clientHeight + 'px',
        question: [], // 问题,
        answer: [], //答案
        showAddress: false, // 省市区展示
        showSchoolsType: false, // 学校类型展示
        showSchools: false, // 学校展示
        showGrade: false, //年级展示
        showClasses: false, //班级展示

        area: '', //省市区
        provinceId: '', //省id
        cityId: '', //市id
        districtId: '', //区域ID
        realName: '', //姓名
        tel: '', //电话
        subLoading: false,
        datas: [], // 所有的数据
        schoolsTypeIndex: 0,
        schoolsTypeData: [], // 学校类型
        schoolsData: [], // 学校
        gradeData: [], //年级
        classesData: [], // 班级

        schoolsType: {
          id: '',
          text: ''
        },

        schools: {
          id: '',
          text: ''
        },

        grade: {
          id: '',
          text: ''
        },

        classes: {
          id: '',
          text: ''
        },

        openid: window.localStorage.openId,
        minheight: document.documentElement.clientHeight + 'px'
      }
    },
    watch: {
      districtId: function (val) {
        this.getData()
        this.schoolsType = {
          id: 0,
          text: ''
        }
        this.schools = {
          id: 0,
          text: ''
        }
        this.classes = {
          id: 0,
          text: ''
        }
        this.grade = {
          id: 0,
          text: ''
        }
      },
      schoolsTypeId: function (val) {
        this.schools = {
          id: 0,
          text: ''
        }
        this.classes = {
          id: 0,
          text: ''
        }
        this.grade = {
          id: 0,
          text: ''
        }
      },
      schoolsId: function (val) {
        this.classes = {
          id: 0,
          text: ''
        }
        this.grade = {
          id: 0,
          text: ''
        }
      },
      gradeId: function (val) {
        this.classes = {
          id: 0,
          text: ''
        }
      },
    },
    methods: {
      radioClick(index, idx) {
        this.$set(this.answer[index], 'a' , [idx])
      },
      checkedClick(index, idx) {
        let a = this.answer[index].a
        const i = a.indexOf(idx)
        if (i > -1) {
          a.splice(i, 1)
          this.$set(this.answer[index], 'a' , a)
        } else {
          this.$set(this.answer[index], 'a' , [...a, idx].sort((a, b) => a - b))
        }
      },
      //选择地区
      handleAreaCofirm(area) {
        this.area = Array.from(area, x => x.name).join(' ')
        this.provinceId = area[0].id
        this.cityId = area[1].id
        this.districtId = area[2].id
      },

      //获取所有数据
      getData() {
        this.$http('/api/common/school', {
          districtId: this.districtId
        }).then(data => {
          this.datas = data
          this.initSchoolsTypeData()
          this.initSchoolsData(0)
          this.initGradeData(0, 0)
          this.initClassesData(0, 0, 0)
        }).catch(err => {

        })
      },

      //初始化学校类型
      initSchoolsTypeData() {
        let schoolsTypeData = Array.from(this.datas, x => ({
          id: x.id,
          text: x.title
        }))
        this.schoolsTypeData = schoolsTypeData
      },

      //初始化学校
      initSchoolsData(index) {
        try {
          const schools = this.datas[index].schools
          let schoolsData = Array.from(schools, x => ({
            id: x.id,
            text: x.title
          }))
          this.schoolsData = schoolsData
        } catch(err) {

        }
      },

      //初始化班级
      initGradeData(index, idx) {
        try {
          const grade = this.datas[index].schools[idx].grade
          let gradeData = Array.from(grade, x => ({
            id: x.id,
            text: x.title
          }))
          this.gradeData = gradeData
        } catch (err) {

        }
      },

      //初始化班级
      initClassesData(index, idx, i) {
        try {
          const classes = this.datas[index].schools[idx].grade[i].classes
          let classesData = Array.from(classes, x => ({
            id: x.id,
            text: x.title
          }))
          this.classesData = classesData
        } catch (err) {

        }
      },

      //显示学校类型picker
      handleShowSchoolsType() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showSchoolsType = true
      },
      //学校类型picker确认
      onSchoolsTypeConfirm(val, index) {
        this.schoolsTypeIndex = index
        this.initSchoolsData(index)
        this.initGradeData(index, 0)
        this.initClassesData(index, 0, 0)
        this.schoolsType = val
        this.showSchoolsType = false
      },

      //显示学校picker
      handleShowSchools() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showSchools = true
      },
      //学校picker确认
      onSchoolsConfirm(val, index) {
        this.initGradeData(this.schoolsTypeIndex, index)
        this.initClassesData(this.schoolsTypeIndex, index, 0)
        this.schools = val
        this.showSchools = false
      },
      //显示年级picker
      handleShowGrade() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showGrade = true
      },
      //显示班级picker
      handleShowClasses() {
        if (!this.districtId){
          this.$toast('请选择学校所在地区')
          return
        }
        this.showClasses = true
      },
      //年级picker确认
      onGradeConfirm(val, index) {
        this.grade = val
        this.initClassesData(this.schoolsTypeIndex, index, 0)
        this.showGrade = false
      },
      //班级picker确认
      onClassesConfirm(val) {
        this.classes = val
        this.showClasses = false
      },

      submit() {
        let  req = {
          provinceId: this.provinceId,
          cityId: this.cityId,
          districtId: this.districtId,
          schoolTypeId: this.schoolsTypeId,
          schoolId: this.schoolsId,
          gradeId: this.gradeId,
          classId: this.classesId,
          realName: this.realName,
          mobile: this.tel,
          answers: this.answer,
          openId: window.localStorage.openId,
        }
        validator.validate(req, (errors, fields) => {
          if(errors) {
            this.$toast(errors[0].message)
          } else {
            this.subLoading = true
            this.$toast.loading({
              mask: true,
              duration: 0,
              message: '正在提交问卷'
            })
            this.$http('/api/question/answer', req).then(res => {
              this.$toast.success('提交成功')
              this.subSuccess = true
            }).catch(err => {
              this.subLoading = false
              this.$toast(err.msg || '提交失败')
            })
          }
        })
      }
    }
  }
</script>

<style scoped>
#questionnaire{
  padding: 10px;
  background: #f2f1f7;
}

.title, .des{
  line-height: 20px;
  margin-bottom: 5px;
}
.question{
  padding: 10px 20px;
  background: #fff;
  margin-top: 10px;
}
.question .item{
  border: 1px solid #dcf0e2;
  position: relative;
}
.question .title{
  padding: 10px 20px;
  min-height: 60px;
  line-height: 20px;
  font-size: 14px;
  color: #048629;
  background: #dcf0e2;
}
.question .daan{
  padding: 5px 20px;
}
.question .wen{
  position: absolute;
  z-index: 1;
  top: -1px;
  left: -15px;
  width: 30px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #048629;
  background: #fff;
  border-radius: 50%;
  border: 1px solid #dcf0e2;
}
  .radio{
    margin-bottom: 10px; padding-left: 1px;
    display: flex;
  }
  .success{
    font-size: 60px;
    color: #19be6b;
  }
</style>

